import { commonIDPage } from '@/common/common'
import { getIndexList } from '@/api/indexCategory'
import type { ApiResponse } from '@/common/requestType'
import type { Data } from '@/common/topic/topicDetailType'
import { searchTieZi, searchUser, searchHuaTi } from '@/api/indexCategory'
import { getTopicList } from '@/api/topic'

export const loadDataCommon = () => {
  // tabbar数据交互
  // 首页（index）/话题详情页(topicDetail)/搜索页(select)
  const position = ref<string>('')
  const {
    loading,
    hasMore,
    tableData,
    page,
    loadData,
    activeId,
    isFirstLoad,
    tab
  } = commonIDPage({
    getList: () => {
      switch (position.value) {
        case 'index':
          // 这里只能使用return 不能使用break
          return getIndexList(activeId.value, page.value)
        case 'select':
          if (activeId.value === 0) {
            return searchTieZi(page.value, tab.value)
          } else if (activeId.value === 1) {
            return searchUser(page.value, tab.value)
          } else {
            // 搜索话题，不需要指定position
            return searchHuaTi(page.value, tab.value)
          }
        // 话题,注意：需要指定position为topic
        case 'topic':
          return getTopicList(activeId.value, page.value)
        default:
          return
      }
    },
    onGetListSuccess: (res: ApiResponse<Data>) => {
      if (res.data.data.length == 0) return
      // 数据是否到底部
      hasMore.value = res.data.current_page >= res.data.last_page
      if (page.value === 1) {
        tableData.value = res.data.data
        console.log(res.data.data)
      } else {
        tableData.value.push(...res.data.data)
      }
      page.value = hasMore.value
        ? res.data.current_page
        : Math.floor(res.data.current_page + 1)
    }
  })
  return {
    loading,
    hasMore,
    tableData,
    page,
    loadData,
    activeId,
    isFirstLoad,
    position,
    tab
  }
}
